﻿using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
using System.Linq;
using OpenCvSharp;
using System.ComponentModel;

namespace Xc.Logics.CodeReaders.Models
{
    [TypeConverter(typeof(ScalarConverter))]
    public class ScalarConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var text = value?.ToString();
            return text;

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var info = typeof(Scalar).GetField(value?.ToString(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.CreateInstance);
            if (info == null)
            {
                var text= value?.ToString();
                var  e= text.Replace("[", String.Empty).Replace("]",String.Empty);
                var array= e.Split(",");
                if (array!=null&&array.Length==4)
                {
                    var arry= array.Select(p => System.Convert.ToDouble(p)).ToArray();
                    return new Scalar(arry[0], arry[1], arry[2], arry[3]);
                }
                else
                {
                    var color = (Color)ColorConverter.ConvertFromString(text);
                    return new Scalar(color.A, color.R, color.G, color.B);
                }
            }
            var d = info.GetValue(Activator.CreateInstance(typeof(Scalar)));
            return d;
        }
    }
}
